<template>
  <div class="flex flex-col h-full overflow-hidden">
    <app-header/>

    <main>
      <form @submit.prevent="saveEventConfig" id="event-config-form-printsn" class="config-form">
        <h2 class="form-title">事件配置 - PrintSN</h2>

        <div class="form-section">
          <h3 class="form-section-title">基本设置</h3>
          <div class="form-group flex items-center gap-4 mb-3">
            <span class="toggle-label">启用此事件</span>
            <label class="switch">
              <input type="checkbox" id="printsn-enabled" v-model="eventConfig.enabled">
              <span class="slider" :class="{ 'checked': eventConfig.enabled }"></span>
            </label>
          </div>
          <p class="form-description mb-4">启用后，打码程序单穴使用时将触发此事件。</p>

          <div class="grid grid-cols-1 sm:grid-cols-2 gap-x-4 gap-y-2">
            <div class="form-group col-span-2">
              <label for="printsn-url" class="form-label">接收 URL <span class="text-red-500">*</span></label>
              <input type="url" id="printsn-url" v-model="eventConfig.url" class="form-input"
                     placeholder="例如: http://mes.example.com/api/printsn" required>
              <p class="form-description">MES 接收 PrintSN 事件数据的 URL。</p>
            </div>

            <div class="form-group">
              <label for="printsn-token" class="form-label">认证 Token <span class="text-red-500">*</span></label>
              <input type="text" id="printsn-token" v-model="eventConfig.TOKEN" class="form-input"
                     placeholder="用于验证是否能调用该接口，需MES提供" required>
              <p class="form-description">用于接口认证。</p>
            </div>
            <div class="form-group">
              <label for="printsn-line" class="form-label">产线 (Line) <span class="text-red-500">*</span></label>
              <input type="text" id="printsn-line" v-model="eventConfig.LINE" class="form-input"
                     placeholder="当前所在产线文档中。以便根据实际情况填写" required>
              <p class="form-description">当前产线编码。</p>
            </div>
            <div class="form-group">
              <label for="printsn-stationid" class="form-label">站点 ID (StationID) <span class="text-red-500">*</span></label>
              <input type="text" id="printsn-stationid" v-model="eventConfig.STATIONID" class="form-input"
                     placeholder="当前所在部门文档中。以便根据实际情况填写" required>
              <p class="form-description">工站程序ID（MES Station）。</p>
            </div>
            <div class="form-group">
              <label for="printsn-machineid" class="form-label">机台 ID (MachineID) <span class="text-red-500">*</span></label>
              <input type="text" id="printsn-machineid" v-model="eventConfig.MACHINEID" class="form-input"
                     placeholder="机台信息" required>
              <p class="form-description">机台信息。</p>
            </div>
            <div class="form-group">
              <label for="printsn-opid" class="form-label">操作员 ID (OPID) <span class="text-red-500">*</span></label>
              <input type="text" id="printsn-opid" v-model="eventConfig.OPID" class="form-input"
                     placeholder="工号或UserID" required>
              <p class="form-description">操作人员ID。</p>
            </div>
            <div class="form-group">
              <label for="printsn-fixsn" class="form-label">固定 SN (FixSN) <span class="text-red-500">*</span></label>
              <input type="text" id="printsn-fixsn" v-model="eventConfig.FIXSN" class="form-input" placeholder="固定SN"
                     required>
              <p class="form-description">固定SN。</p>
            </div>
          </div>
        </div>

        <!-- 动态数据部分 -->
        <div class="form-section">
          <h3 class="form-section-title">动态数据</h3>
          <p class="form-description mb-4">以下数据在打印SN时动态添加</p>

          <div class="grid grid-cols-1 sm:grid-cols-2 gap-x-4 gap-y-2">
            <div class="form-group">
              <label for="test-wo" class="form-label">工单号 (WO)</label>
              <input type="text" id="test-wo" v-model="eventConfig.WO" class="form-input" placeholder="打印时的工单">
              <p class="form-description">打印的工单。</p>
            </div>
            <div class="form-group">
              <label for="test-qty" class="form-label">数量 (Qty)</label>
              <input type="number" id="test-qty" v-model="eventConfig.Qty" class="form-input" min="1" max="100"
                     placeholder="需要打印的SN数量">
              <p class="form-description">需要打印的SN数量。</p>
            </div>
            <div class="form-group">
              <label class="form-label">发送时间 (SendTime)</label>
              <input type="text" class="form-input" :value="getCurrentDateTime()" disabled>
              <p class="form-description">机台发送事件的时间。</p>
            </div>
          </div>
        </div>

        <!-- 测试事件部分 -->
        <div class="form-section">
          <h3 class="form-section-title">事件测试</h3>

          <div class="mt-4">
            <button type="button" class="hmi-button hmi-button-primary"
                    @click="testPrintSNEvent"
                    :disabled="isTesting || !eventConfig.enabled || !eventConfig.url">
              <i :class="isTesting ? 'fas fa-spinner fa-spin' : 'fas fa-paper-plane'"></i>
              {{ isTesting ? '测试中...' : '发送测试请求' }}
            </button>
          </div>

          <div v-if="testResult.show" class="mt-4 p-4 rounded-md text-sm"
               :class="{'bg-green-50 border border-green-200': testResult.success, 'bg-red-50 border border-red-200': !testResult.success}">
            <div class="font-semibold mb-2"
                 :class="{'text-green-700': testResult.success, 'text-red-700': !testResult.success}">
              {{ testResult.success ? '测试成功' : '测试失败' }}
            </div>
            <div class="text-gray-700 mb-2">{{ testResult.message }}</div>
            <pre v-if="testResult.data" class="bg-gray-100 p-2 rounded text-xs overflow-auto max-h-40">{{
                JSON.stringify(testResult.data, null, 2)
              }}</pre>
          </div>
        </div>

        <div class="button-group">
          <button type="button" id="btn-cancel-event-config" class="hmi-button hmi-button-secondary" @click="goBack">
            <i class="fas fa-times"></i>取消
          </button>
          <button type="submit" id="btn-save-event-config" class="hmi-button hmi-button-primary" :disabled="isSaving">
            <i :class="isSaving ? 'fas fa-spinner fa-spin' : 'fas fa-save'"></i>{{
              isSaving ? '保存中...' : '保存配置'
            }}
          </button>
        </div>
      </form>
    </main>

    <div v-if="notification.show" id="notification" class="notification"
         :class="{ 'notification-success': notification.type === 'success', 'notification-error': notification.type === 'error', 'show': notification.show }">
      <span id="notification-message">{{ notification.message }}</span>
    </div>
  </div>
</template>

<script setup>
import {ref, reactive, onMounted, onBeforeUnmount, watch} from 'vue'
import {useRouter} from 'vue-router' // 导入 useRouter 和 onBeforeRouteLeave
// 导入MES事件服务
import {getMesEventConfig, saveMesEventConfig} from '@/api/mesEvent';
const eventName = 'PrintSN'
// 不再需要导入 AppHeader，因为它已全局配置

const router = useRouter() // 获取路由实例



// --- 响应式数据 ---
// 事件配置数据 (实际应用中应从 API 或配置文件加载)
const eventConfig = reactive({
  "enabled": false,
  "url": '',
  "EVENTID": "",
  "LINE": "",
  "STATIONID": "",
  "TOKEN": "",
  "FIXSN": "",
  "MACHINEID": "",
  "OPID": "",
  "SENDTIME": "",
  "WO": "",
  "QTY": "",
  "TRANSID": ""
})

// 用于跟踪表单是否有未保存的更改
const isSaving = ref(false) // 用于控制保存按钮的加载状态

// 通知状态
const notification = reactive({
  show: false,
  message: '',
  type: 'success', // 'success' or 'error'
  timeoutId: null // 用于存储定时器ID
})

// 记录加载时的原始配置，用于判断是否有更改
let initialEventConfig = {}

// 测试状态
const isTesting = ref(false)
const testResult = reactive({
  show: false,
  success: false,
  message: '',
  data: null
})

// --- 方法 ---

// 获取当前日期时间格式化字符串，用于 SendTime
const getCurrentDateTime = () => {
  const now = new Date();
  return now.getFullYear() + '/' +
      String(now.getMonth() + 1).padStart(2, '0') + '/' +
      String(now.getDate()).padStart(2, '0') + ' ' +
      String(now.getHours()).padStart(2, '0') + ':' +
      String(now.getMinutes()).padStart(2, '0') + ':' +
      String(now.getSeconds()).padStart(2, '0');
}

// 显示通知
const showNotification = (message, type = 'success') => {
  notification.show = true
  notification.message = message
  notification.type = type
  if (notification.timeoutId) {
    clearTimeout(notification.timeoutId)
  }
  notification.timeoutId = setTimeout(() => {
    notification.show = false
  }, 3000)
}

// 加载事件配置 (模拟从后端获取)
const loadEventConfig = () => {
  getMesEventConfig(eventName).then(data => {
    Object.assign(eventConfig, data)
    console.log(data)
  })
}

// 保存事件配置
const saveEventConfig = () => {
  const form = document.getElementById('event-config-form-printsn')
  // 使用 Vue 的 $refs 或获取DOM元素进行验证
  if (!form || !form.checkValidity()) {
    showNotification('请填写所有必填项 (*)', 'error')
    // 触发表单的原生验证提示
    if (form) form.reportValidity()
    return
  }

  isSaving.value = true // 显示保存中状态

  // 构建要保存的数据对象 (深拷贝)
  const dataToSave = JSON.parse(JSON.stringify(eventConfig))
  //保存
  saveMesEventConfig(eventName, dataToSave).then(res => {
    if (res.code === 200) {
      showNotification('PrintSN 配置保存成功!', 'success')
      goBack()
    }
  })
}

// 导航回上一页，检查未保存更改 (通常是事件配置导航页)
const goBack = () => {
  router.back() // 使用 Vue Router 返回上一页
}

// 测试 PrintSN 事件
const testPrintSNEvent = async () => {

}


// --- 生命周期钩子 ---
onMounted(() => {
  // 页面挂载后加载配置数据
  loadEventConfig()
})

onBeforeUnmount(() => {
  // 清理通知定时器
  if (notification.timeoutId) {
    clearTimeout(notification.timeoutId)
  }
})

// ESC键返回功能可以通过 Vue Router 的 beforeEach 或组件内部监听实现
// 如果需要在单个组件内实现ESC返回，可以在 mounted 中添加监听，在 unmounted 中移除
onMounted(() => {
  const handleEscape = (event) => {
    if (event.key === 'Escape') {
      // 触发与取消按钮相同的逻辑，包括未保存检查
      goBack()
    }
  }
  document.addEventListener('keydown', handleEscape)
  onMounted(() => {
    document.removeEventListener('keydown', handleEscape)
  })
})

</script>

<style scoped>
/* --- 将原始 HTML 文件中的所有自定义样式复制到这里 --- */


/* --- Main Content Area --- */
main {
  flex-grow: 1;
  padding: 1.5rem;
  overflow-y: auto; /* Enable scrolling for form */
}

/* --- Configuration Form --- */
.config-form {
  background-color: var(--bg-secondary);
  border-radius: 0.75rem;
  box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.05), 0 2px 4px -2px rgba(0, 0, 0, 0.05);
  padding: 1.5rem;
  border: 1px solid var(--border-color);
  max-width: 900px; /* Adjust max width for this form */
  margin: 0 auto; /* Center form */
}

.form-title {
  font-size: 1.1rem;
  font-weight: 700;
  color: var(--text-primary);
  margin-bottom: 1.5rem;
  text-align: center;
  border-bottom: 1px solid var(--border-color);
  padding-bottom: 0.75rem;
}

.form-section {
  margin-bottom: 1.5rem;
}

.form-section-title {
  font-size: 0.9rem;
  font-weight: 600;
  color: var(--text-primary);
  margin-bottom: 0.75rem;
  border-left: 3px solid var(--accent-blue);
  padding-left: 0.5rem;
}

.form-group {
  margin-bottom: 1rem;
}

.form-label {
  display: block;
  font-size: 0.8rem;
  font-weight: 500;
  color: var(--text-secondary);
  margin-bottom: 0.25rem;
}

.form-input, .form-select {
  width: 100%;
  padding: 0.5rem 0.75rem;
  border: 1px solid var(--border-color);
  border-radius: 0.5rem;
  font-size: 0.875rem;
  transition: border-color 0.2s ease, box-shadow 0.2s ease;
  background-color: #f9fafb;
}

.form-input:focus, .form-select:focus {
  outline: none;
  border-color: var(--accent-blue);
  box-shadow: 0 0 0 2px rgba(59, 130, 246, 0.3);
  background-color: white;
}

.form-input:required:invalid, .form-select:required:invalid {
  border-color: var(--status-red);
}

.form-input[readonly] {
  background-color: #e5e7eb;
  cursor: not-allowed;
  opacity: 0.7;
  color: var(--text-secondary);
}

.form-select {
  appearance: none;
  background-image: url("data:image/svg+xml,%3csvg xmlns='http://www.w3.org/2000/svg' fill='none' viewBox='0 0 20 20'%3e%3cpath stroke='%236b7280' stroke-linecap='round' stroke-linejoin='round' stroke-width='1.5' d='M6 8l4 4 4-4'/%3e%3csvg%3e");
  background-position: right 0.5rem center;
  background-repeat: no-repeat;
  background-size: 1.5em 1.5em;
  padding-right: 2.5rem;
}

.form-description {
  font-size: 0.7rem;
  color: var(--text-tertiary);
  margin-top: 0.25rem;
}

/* Input group for select + button (if any) */
.input-button-group {
  display: flex;
  gap: 0.5rem;
  align-items: center;
}

.input-button-group .form-select {
  flex-grow: 1;
}

.input-button-group .hmi-button {
  flex-shrink: 0;
}


/* Toggle Switch */
.toggle-switch {
  display: flex;
  align-items: center;
  gap: 1rem;
}

.toggle-label {
  font-size: 0.8rem;
  font-weight: 500;
  color: var(--text-secondary);
  flex-shrink: 0;
}

.switch {
  position: relative;
  display: inline-block;
  width: 40px;
  height: 20px;
  flex-shrink: 0;
}

.switch input {
  opacity: 0;
  width: 0;
  height: 0;
}

.slider {
  position: absolute;
  cursor: pointer;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: #ccc;
  transition: .4s;
  border-radius: 20px;
}

.slider:before {
  position: absolute;
  content: "";
  height: 14px;
  width: 14px;
  left: 3px;
  bottom: 3px;
  background-color: white;
  transition: .4s;
  border-radius: 50%;
}

/* Apply background color based on checked state in Vue with binding */
.slider.checked {
  background-color: var(--accent-blue);
}

/* Apply transform based on checked state in Vue with binding */
input:checked + .slider:before {
  transform: translateX(20px);
}


/* --- Buttons --- */
.button-group {
  display: flex;
  gap: 1rem;
  justify-content: flex-end;
  margin-top: 2rem;
  border-top: 1px solid var(--border-color);
  padding-top: 1.5rem;
}

.hmi-button {
  padding: 0.6rem 1.2rem;
  border-radius: 0.5rem;
  font-size: 0.875rem;
  font-weight: 600;
  display: inline-flex;
  align-items: center;
  justify-content: center;
  gap: 0.4rem;
  border: 1px solid transparent;
  transition: all 0.2s ease;
  cursor: pointer;
}

/* Adjusted padding for small button */
.hmi-button-small {
  padding: 0.35rem 0.7rem;
  font-size: 0.75rem;
}

.hmi-button i {
  font-size: 1em;
}

/* HMI Button Colors - Defined by variables */
.hmi-button-primary {
  background-color: var(--accent-blue);
  color: white;
  border-color: var(--accent-blue);
}

.hmi-button-primary:hover {
  background-color: #2563eb;
  border-color: #2563eb;
}

/* Specific hover color */
.hmi-button-secondary {
  background-color: var(--bg-secondary);
  color: var(--text-primary);
  border-color: var(--border-color);
}

.hmi-button-secondary:hover {
  background-color: #f9fafb;
  border-color: #d1d5db;
}

/* Specific hover color */
.hmi-button:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

/* --- Notification --- */
.notification {
  position: fixed;
  bottom: 1rem;
  left: 50%;
  transform: translateX(-50%);
  padding: 0.75rem 1.25rem;
  border-radius: 0.5rem;
  color: white;
  font-size: 0.875rem;
  font-weight: 500;
  box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
  opacity: 0;
  visibility: hidden;
  transition: opacity 0.3s ease, visibility 0.3s ease;
  z-index: 100;
}

.notification.show {
  opacity: 1;
  visibility: visible;
}

/* Notification Colors - Defined by variables */
.notification-success {
  background-color: var(--status-green);
}

.notification-error {
  background-color: var(--status-red);
}


/* Body styles from original inline style */
/* max-width: 800px; max-height: 600px; margin: auto; */
/* These should ideally be managed in a layout component or App.vue */

</style>
